<?php
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\mall\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\mall\model\Category as CategoryModel;
use app\mall\model\Goods as GoodsModel;
use app\user\model\Level;
use app\user\model\Level as LevelModel;
use app\user\model\User as UserModel;
use think\Db;
use util\Tree;

/**
 * 产品控制器
 * @package app\mall\admin
 */
class Goods extends Admin
{
    /**
     * 产品列表
     */
    public function index($cid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map   = $this->getMap();
		if($cid > 0){
			$map[] = ['mall_goods.cid', '=', $cid];
		}
		$category = CategoryModel::where('status', 1)->column('title','id');
		//dump($category);
        // 排序
        $order = $this->getOrder('status desc,id');
        // 数据列表
        $data_list = GoodsModel::getList($map, $order);


        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['mall_goods.title' => '商品标题', 'mall_category.title' => '分类名称']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['title', '商品标题', 'text'],
                ['cid', '分类名称', 'callback', function($value){return CategoryModel::where('id', $value)->value('title');}],
                ['agent', '代理类型', 'callback', function($value){return Level::agent_list($value);}],
				['price', '零售单价（元）', 'callback', function($value){return $value / 100;}],
                ['price_pifa', '批发单价（元）', 'callback', function($value){return $value / 100;}],
                ['price_xian', '县代单价（元）', 'callback', function($value){return $value / 100;}],
                ['price_shi', '市代单价（元）', 'callback', function($value){return $value / 100;}],
                ['price_sheng', '省代单价（元）', 'callback', function($value){return $value / 100;}],
				['number', '库存', 'text.edit'],
				['update_time', '更新时间', 'datetime'],
                ['sort', '排序', 'text.edit'],
				['index', '首页推荐', 'switch'],
                ['status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons(['edit', 'delete']) // 批量添加右侧按钮
            ->addOrder(['category_name' => 'mall_goods.cid'])
            ->addOrder('id,title,update_time')
			->addFilterList('cid', $category)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }

    /**
     * 添加产品
     * @param int $cid 栏目id
     * @param string $model 模型id
     * @return mixed
     * @throws \think\Exception
     */
    public function add($cid = 0)
    {

        // 保存产品数据
        if ($this->request->isAjax()) {
			$data = request()->post();
            // 验证
			$data['price'] = $data['price'] * 100;
            $data['price_pifa'] = $data['price_pifa'] * 100;
            $data['price_xian'] = $data['price_xian'] * 100;
            $data['price_qu'] = $data['price_qu'] * 100;
            $data['price_shi'] = $data['price_shi'] * 100;
            $data['price_sheng'] = $data['price_sheng'] * 100;
            $data['er_price_xian'] = $data['er_price_xian'] * 100;
            $data['er_price_qu'] = $data['er_price_qu'] * 100;
            $data['er_price_shi'] = $data['er_price_shi'] * 100;
            $data['er_price_sheng'] = $data['er_price_sheng'] * 100;
            $data['san_price_xian'] = $data['san_price_xian'] * 100;
            $data['san_price_qu'] = $data['san_price_qu'] * 100;
            $data['san_price_shi'] = $data['san_price_shi'] * 100;
            $data['san_price_sheng'] = $data['san_price_sheng'] * 100;
			
			$result = $this->validate($data, 'Goods');
			if(true !== $result) $this->error($result);
			
            if ($goods = GoodsModel::create($data)) {
                // 记录行为
                action_log('goods_add', 'mall_goods', $goods['id'], UID, $data['title']);
                $this->success('新增成功', cookie('__forward__'));
            } else {
                $this->error('新增失败');
            }  
        }
		
		$category_list = CategoryModel::getTreeList(0, false);
        $level_list = LevelModel::select()->toArray();

        // 第1步，填写产品信息
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		$can_buy = LevelModel::shop_list();
        $agent_list = LevelModel::agent_list();
		unset($can_buy[0]);
		// 使用ZBuilder快速创建表单
		return ZBuilder::make('form')
			->addGroup([
				'基本信息' =>[
					['hidden', 'id'],
					['select', 'cid', '所属分类', '<span class="text-danger">必选</span>', $category_list],
                    ['select', 'agent', '所属代理类型', '<span class="text-danger">必选</span>', $agent_list],
					['text', 'title', '商品标题', '<span class="text-danger">必填</span>'],
					['image', 'logo', '商品封面', ''],
                    ['file', 'goods_video', '视频', ''],
					['images', 'pics', '组图', ''],
					['wangeditor:8', 'content', '商品图文', ''],
					['textarea:8', 'summary', '简介', ''],
				],
				'商品参数' =>[
					['text', 'code', '商品条码', ''],
                    ['text:8', 'price', '商品零售单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
					['text:8', 'weight', '重量', '单位：千克'],
					['text:8', 'number', '库存', '请填写整数'],
					['text:8', 'canbuy', '限购', '每人限购个数，0为不限购', 0],
					// ['checkbox', 'group', '允许购买的店', '', LevelModel::shop_list(), array_keys($can_buy)],
				],
                '一代政策' =>[
                    ['text:8', 'price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
                '二代政策' =>[
                    ['text:8', 'er_price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
                '三代政策' =>[
                    ['text:8', 'san_price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
				'商品设置' =>[
					// ['text:8', 'view', '浏览量', '', 0],
					// ['text:8', 'comment', '评论数', '', 0],
					// ['text:8', 'good', '赞', '', 0],
					// ['text:8', 'bad', '踩', '', 0],
					
					['radio:8', 'discount', '开启折扣', '', ['否', '是'], 1],
					['radio:8', 'rebate', '开启返佣', '', ['否', '是'], 1 ],
					['radio:8', 'balance', '开启首购余额', '', ['否', '是'], 1 ],
					['radio:8', 'index', '推荐到首页', '', ['否', '是'], 0],
					['radio:8', 'status', '启用', '', ['否', '是'], 1 ],
				],
			])
			->layout(['cid' => 8, 'title' => 8, 'avatar' => 12,'zhiwu' => 8, 'mobile' => 8, 'code' => 8, 'uid' => 8])
			->fetch();
    }

    /**
     * 编辑产品
     * @param null $id 产品id
     * @param string $model 模型id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('参数错误');
		
		$info = GoodsModel::getOne($id);
		$info['price'] = $info['price'] / 100;
        $info['price_pifa'] = $info['price_pifa'] / 100;
        $info['price_xian'] = $info['price_xian'] / 100;
        $info['price_qu'] = $info['price_qu'] / 100;
        $info['price_shi'] = $info['price_shi'] / 100;
        $info['price_sheng'] = $info['price_sheng'] / 100;
        $info['er_price_xian'] = $info['er_price_xian'] / 100;
        $info['er_price_qu'] = $info['er_price_qu'] / 100;
        $info['er_price_shi'] = $info['er_price_shi'] / 100;
        $info['er_price_sheng'] = $info['er_price_sheng'] / 100;
        $info['san_price_xian'] = $info['san_price_xian'] / 100;
        $info['san_price_qu'] = $info['san_price_qu'] / 100;
        $info['san_price_shi'] = $info['san_price_shi'] / 100;
        $info['san_price_sheng'] = $info['san_price_sheng'] / 100;

        // 保存产品数据
        if ($this->request->isPost()) {
			$data = request()->post();

            $data['price'] = $data['price'] * 100;
            $data['price_pifa'] = $data['price_pifa'] * 100;
            $data['price_xian'] = $data['price_xian'] * 100;
            $data['price_qu'] = $data['price_qu'] * 100;
            $data['price_shi'] = $data['price_shi'] * 100;
            $data['price_sheng'] = $data['price_sheng'] * 100;
            $data['er_price_xian'] = $data['er_price_xian'] * 100;
            $data['er_price_qu'] = $data['er_price_qu'] * 100;
            $data['er_price_shi'] = $data['er_price_shi'] * 100;
            $data['er_price_sheng'] = $data['er_price_sheng'] * 100;
            $data['san_price_xian'] = $data['san_price_xian'] * 100;
            $data['san_price_qu'] = $data['san_price_qu'] * 100;
            $data['san_price_shi'] = $data['san_price_shi'] * 100;
            $data['san_price_sheng'] = $data['san_price_sheng'] * 100;

            var_dump($data);exit;
			// 验证
			$result = $this->validate($data, 'Goods');
			if(true !== $result) $this->error($result);
			
            if ($goods = GoodsModel::update($data)) {
                // 记录行为
                action_log('goods_edit', 'mall_goods', $goods['id'], UID, $data['title']);
                $this->success('更新成功', cookie('__forward__'));
            } else {
                $this->error('更新失败');
            }
        }
		
		$category_list = CategoryModel::getTreeList(0, false);
        $agent_list = LevelModel::agent_list();
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
			->addGroup([
				'基本信息' =>[
					['hidden', 'id'],
					['select', 'cid', '所属分类', '<span class="text-danger">必选</span>', $category_list, $info['cid']],
                    ['select', 'agent', '所属代理类型', '<span class="text-danger">必选</span>', $agent_list],
					['text', 'title', '商品标题', '<span class="text-danger">必填</span>'],
					['image', 'logo', '商品封面', ''],
                    ['file', 'goods_video', '视频', ''],
					['images', 'pics', '组图', ''],
					['wangeditor:8', 'content', '商品图文', ''],
					['textarea:8', 'summary', '简介', ''],
				],
				'商品参数' =>[
					['text', 'code', '商品条码', ''],
					['text:8', 'price', '零售单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
					['text:8', 'weight', '重量', '单位：千克'],
					['text:8', 'number', '库存', '请填写整数'],
					['text:8', 'transport', '快递费', ''],
					['text:8', 'canbuy', '限购', '每人限购个数，0为不限购'],
					// ['checkbox', 'group', '允许购买的店', '', LevelModel::shop_list()],
				],
                '一代政策' =>[
                    ['text:8', 'price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
                '二代政策' =>[
                    ['text:8', 'er_price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'er_price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
                '三代政策' =>[
                    ['text:8', 'san_price_pifa', '商品批发单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_xian', '商品街道单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_qu', '商品区县级单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_shi', '商品县级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                    ['text:8', 'san_price_sheng', '商品地级市单价', '','', ['<i class="fa fa-fw fa-yen"></i>', '']],
                ],
				'商品设置' =>[
					// ['text:8', 'view', '浏览量', ''],
					// ['text:8', 'comment', '评论数', ''],
					// ['text:8', 'good', '赞', ''],
					// ['text:8', 'bad', '踩', ''],
					
					['radio:8', 'discount', '开启折扣', '', ['否', '是']],
					['radio:8', 'rebate', '开启返佣', '', ['否', '是'] ],
					['radio:8', 'balance', '开启首购余额', '', ['否', '是']],
					// ['radio:8', 'money_se', '开启复购余额', '', ['否', '是']],
					['radio:8', 'index', '推荐到首页', '', ['否', '是']],
					['radio:8', 'status', '启用', '', ['否', '是']],
				],
			])
			->layout(['cid' => 8, 'title' => 8, 'avatar' => 12,'zhiwu' => 8, 'mobile' => 8, 'code' => 8, 'uid' => 8])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除产品(不是彻底删除，而是移动到回收站)
     * @param null $ids 产品id
     * @param string $table 数据表
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用产品
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用产品
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置产品状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $goods_title = GoodsModel::where('id', 'in', $ids)->column('title');
        return parent::setStatus($type, ['goods_'.$type, 'mall_goods', 0, UID, implode('、', $goods_title)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $goods    = GoodsModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $goods . ')，新值：(' . $value . ')';
        return parent::quickEdit(['goods_edit', 'mall_goods', $id, UID, $details]);
    }
}
